import datetime

import sqlalchemy
from flask import Blueprint, request, session, redirect, url_for, jsonify, render_template, json
from sqlalchemy import func, or_, desc

from models import User, db, Bottle, Message

bp = Blueprint('message', __name__)


@bp.route('/addmes', methods=['GET', 'POST'])
def addMes():
    # 未登录
    if 'username' not in session:
        return jsonify({'error': '你还没有到海边~'})

    if request.method == 'POST':
        data = request.json
        username = data.get('reuser')
        userid = data.get('reuser')
        content = data.get('recontent')
        reid = data.get('reid')
        couser = data.get('couser')

        if len(username) < 1 or len(str(userid)) < 1 or len(str(content)) < 1:
            return jsonify({'error': '消息不完整'})
        current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        client_ip = request.remote_addr
        message = Message(recontent=content, reuser=username, reip=client_ip, retime=current_time, reid=reid, couser=couser)
        db.session.add(message)
        try:
            db.session.commit()
            return jsonify({'success': '成功发送消息'})
        except sqlalchemy.exc.SQLAlchemyError:
            return jsonify({'error': '核废水冲散了你的消息，请稍后重试'})

    return jsonify({'error': '核废水流到了大海，请稍后重试'})



@bp.route('/meslist', methods=['GET', 'POST'])
def mesList():
    # 未登录
    if 'username' not in session:
        return jsonify({'error': '你还没有到海边~'})

    if request.method == 'POST':
        data = request.json
        username = data.get('username')
        userid = data.get('userid')
        if len(username) < 1 or len(userid) < 1:
            return jsonify({'error': '你是谁???'})


        messages = Message.query.filter(or_(Message.reuser == username, Message.couser == username)). \
            order_by(desc(Message.retime)).all()
        if not messages:
            # 数据库中没有满足条件的记录
            return jsonify({'error': '你还没有漂流瓶'})

        try:
            data = []
            for message in messages:
                if username != message.reuser:
                    data.append({
                        'content': message.recontent,
                        'settime': message.retime,
                        'setuser': message.reuser,
                        'type': '接收'
                    })
                else:
                    data.append({
                        'content': message.recontent,
                        'settime': message.retime,
                        'setuser': message.reuser,
                        'type': '发送'
                    })
            return jsonify({'state': 200, 'message': data})
        except sqlalchemy.exc.SQLAlchemyError:
            return jsonify({'error': '核废水冲散了你的信息，请稍后重试'})

    return jsonify({'error': '核废水流到了大海，请稍后重试'})
